package com.bai.localshop.service.impl;

import com.bai.localshop.exception.BaseException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bai.localshop.context.BaseContext;
import com.bai.localshop.mapper.AddressBookMapper;
import com.bai.localshop.pojo.dto.AddressAddDTO;
import com.bai.localshop.pojo.dto.AddressUpdateDTO;
import com.bai.localshop.pojo.entity.AddressBook;
import com.bai.localshop.pojo.vo.AddressVO;
import com.bai.localshop.service.AddressBookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    private final AddressBookMapper addressBookMapper;

    private Long getCurrentUserId() {
        return BaseContext.getCurrentId();
    }

    @Override
    @Transactional
    public Long addAddress(AddressAddDTO addressAddDTO) {
        Long userId = getCurrentUserId();

        if (addressAddDTO.getIsDefault() != null && addressAddDTO.getIsDefault() == 1) {
            baseMapper.clearDefaultAddress(userId);
        }

        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressAddDTO, addressBook);
        addressBook.setUserId(userId);
        addressBookMapper.insert(addressBook);
        return addressBook.getId();
    }

    @Override
    @Transactional
    public void updateAddress(AddressUpdateDTO addressUpdateDTO) {
        Long userId = getCurrentUserId();
        AddressBook existingAddress = addressBookMapper.selectById(addressUpdateDTO.getId());
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            throw new BaseException("地址不存在或无权操作");
        }

        if (addressUpdateDTO.getIsDefault() != null && addressUpdateDTO.getIsDefault() == 1) {
            baseMapper.clearDefaultAddress(userId);
        }

        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(addressUpdateDTO, addressBook);
        addressBook.setUserId(userId);
        LambdaUpdateWrapper<AddressBook> updateWrapper = Wrappers.lambdaUpdate(AddressBook.class)
                .set(AddressBook::getUserId, userId)
                .eq(AddressBook::getId, addressBook.getId());
        addressBookMapper.update(addressBook, updateWrapper);
    }

    @Override
    public void deleteAddress(Long addressId) {
        Long userId = getCurrentUserId();

        AddressBook existingAddress = addressBookMapper.selectById(addressId);
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            throw new BaseException("地址不存在或无权操作");
        }

        if (existingAddress.getIsDefault() == 1) {
            log.info("删除了默认地址，用户ID: {}", userId);
        }
        addressBookMapper.deleteById(addressId);
    }

    @Override
    @Transactional
    public void setDefaultAddress(Long addressId) {
        Long userId = getCurrentUserId();

        AddressBook existingAddress = addressBookMapper.selectById(addressId);
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            throw new BaseException("地址不存在或无权操作");
        }

        baseMapper.clearDefaultAddress(userId);
        baseMapper.setDefaultAddress(addressId, userId);
    }

    @Override
    public AddressVO getAddressDetail(Long addressId) {
        Long userId = getCurrentUserId();
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.lambdaQuery(AddressBook.class)
                .eq(AddressBook::getId, addressId)
                .eq(AddressBook::getUserId, userId);
        AddressBook addressBook = addressBookMapper.selectOne(queryWrapper);
        if (addressBook == null) {
            throw new BaseException("地址不存在");
        }

        return convertToVO(addressBook);
    }

    @Override
    public List<AddressVO> getUserAddressList() {
        Long userId = getCurrentUserId();
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.lambdaQuery(AddressBook.class)
                .eq(AddressBook::getUserId, userId)
                .orderByDesc(AddressBook::getIsDefault)
                .orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBooks = addressBookMapper.selectList(queryWrapper);

        return addressBooks.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public AddressVO getDefaultAddress() {
        Long userId = getCurrentUserId();

        AddressBook addressBook = this.getOne(new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1));

        return addressBook != null ? convertToVO(addressBook) : null;
    }

    private AddressVO convertToVO(AddressBook addressBook) {
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(addressBook, addressVO);
        return addressVO;
    }
}